package com.itheima.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.sql.DataSource;

public class AOPAdvice {

     Throwable throwable;
     @Autowired
     DataSource dataSource;

    //事务管理器对象
    PlatformTransactionManager transactionManager = null;
    //事务详情对象
    TransactionDefinition transactionDefinition = null;
    //事务状态对象
    TransactionStatus transactionStatus = null;

    //环绕增强
    //around的返回值就是原始方法的返回值,没有返回值可以是void,有返回值用object
    public void around(ProceedingJoinPoint proceedingJoinPoint) {

        try {
            //事务
            transactionManager = new DataSourceTransactionManager(dataSource);
            transactionDefinition = new DefaultTransactionDefinition();
            transactionStatus = transactionManager.getTransaction(transactionDefinition);

            System.out.println("前值增强:准备转账...");
            //环绕增强 必须调用原始方法
            proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
            System.out.println("后置增强:转账正常完成...");
            //提交事务
            transactionManager.commit(transactionStatus);

        } catch (Throwable t) {
            throwable = t;
            //异常回滚
            transactionManager.rollback(transactionStatus);
            System.out.println("异常增强:转账异常,撤销操作...");
        }finally {
            if (throwable == null){
                System.out.println("最终增强:转账流程 正常 结束");
            } else {
                System.out.println("最终增强:转账流程 异常 结束");
            }
        }
    }
}